import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/dictionary/dictionary_provider.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:base_lib/router/routers.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:doctor_prescribe_lib/western_medicine/edit_medical/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import '../medical_search/entity/medical_search_entity.dart'
    as MedicalSearchBean;
import 'package:base_lib/dictionary/entity/medical_single_dose_entity.dart'
    as SingleDoseBean;
import 'package:base_lib/dictionary/entity/medical_treat_frequency_entity.dart'
    as TreatBean;
import 'package:base_lib/dictionary/entity/medical_treat_route_entity.dart'
    as TreatRouteBean;

///用法用量
class MedicalEditPage extends BaseBlocPage<EditMedicalBloc, _State> {
  MedicalEditPage(Parameters parameters) : super(parameters);

  @override
  _State generateThemeState() {
    return _State();
  }
}

class _State extends BaseBlocPageState<EditMedicalBloc> {

  TextEditingController singleDoseTC = TextEditingController();
  TextEditingController useDayTC = TextEditingController();
  TextEditingController medicineNumTC = TextEditingController();

  TextEditingController remarkTC;

  @override
  void dispose() {
    super.dispose();
    singleDoseTC.dispose();
    useDayTC.dispose();
    medicineNumTC.dispose();
    remarkTC?.dispose();
  }

  @override
  void initState() {
    super.initState();
    MedicalSearchBean.Datas data = parameters.getObj('item');
    bloc.getMedicineInfo(context, data, parameters.getBool('isEdit') ?? false);
  }

  TextStyle leftTs = TextStyle(fontSize: 14, color: Colors.black87);
  TextStyle rightTs = TextStyle(fontSize: 13, color: Colors.black87);
  TextStyle rightGreyTs = TextStyle(fontSize: 13, color: Colors.grey);

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(
          onPressed: () {
            Routers.pop(context);
          },
        ),
        centerTitle: true,
        title: Text('用法用量'),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: SingleChildScrollView(
          child: StreamBuilder(
            stream: bloc.infoStream.stream,
            builder: (context, AsyncSnapshot<MedicalSearchBean.Datas> infoshot) {
              var item = infoshot?.data;
              return infoshot.connectionState == ConnectionState.waiting
                  ? buildLoadingIndicator()
                  : Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          item.medicineName,
                          style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: Colors.black),
                        ),
                        5.vGapDp,
                        Text(
                          "厂商:${item.productFactory}",
                          style: TextStyle(fontSize: 13, color: Colors.black87),
                        ),
                        10.vGapDp,
                        1.gapV(Colors.grey[300]),
                        Row(
                          children: [
                            Text(
                              '单次药量',
                              style: leftTs,
                            ),
                            10.hGapDp,
                            Expanded(
                              child: TextField(
                                controller: singleDoseTC
                                  ..value.copyWith(
                                      text: item.takeDose?.toString() ?? ''),
                                textAlign: TextAlign.right,
                                keyboardType: TextInputType.phone,
                                decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintStyle: rightGreyTs,
                                    hintText: '请输入单次药量'),
                                onChanged: (str) {
                                  bloc.setSingleDose(str);
                                },
                              ),
                            ),
                            StreamBuilder(
                                stream: bloc.singleUnitStream.stream,
                                builder: (context, snapshot) {
                                  return !snapshot.hasData
                                      ? SizedBox()
                                      : Text(
                                          '${snapshot.data.dictName}/次',
                                          style: rightTs,
                                        );
                                }),
                            IconButton(
                              onPressed: () async {
                                FocusScope.of(context).unfocus();
                                bloc.showSingleUnitPicker(context);
                              },
                              icon: Icon(
                                Icons.arrow_forward_ios,
                                color: Colors.grey,
                                size: 12,
                              ),
                            )
                          ],
                        ),
                        1.gapV(Colors.grey[300]),
                        Row(
                          children: [
                            Text(
                              '给药频率',
                              style: leftTs,
                            ),
                            10.hGapDp,
                            Expanded(
                              child: StreamBuilder(
                                  stream: bloc.treatStream.stream,
                                  builder: (context, snapshot) {
                                    return Text(
                                      !snapshot.hasData
                                          ? '请选择'
                                          : snapshot.data.dictName,
                                      style: rightGreyTs,
                                      textAlign: TextAlign.right,
                                    );
                                  }),
                            ),
                            IconButton(
                              onPressed: () async {
                                FocusScope.of(context).unfocus();
                                bloc.showTreatFrequencyPicker(context);
                              },
                              icon: Icon(
                                Icons.arrow_forward_ios,
                                color: Colors.grey,
                                size: 12,
                              ),
                            )
                          ],
                        ),
                        1.gapV(Colors.grey[300]),
                        Row(
                          children: [
                            Text(
                              '给药途径',
                              style: leftTs,
                            ),
                            10.hGapDp,
                            Expanded(
                              child: StreamBuilder(
                                stream: bloc.treatRouteStream.stream,
                                builder: (context, snapshot) {
                                  return Text(
                                    !snapshot.hasData
                                        ? '请选择'
                                        : snapshot.data.dictName,
                                    style: rightGreyTs,
                                    textAlign: TextAlign.right,
                                  );
                                },
                              ),
                            ),
                            IconButton(
                              onPressed: () {
                                FocusScope.of(context).unfocus();
                                bloc.showTreatRoutePicker(context);
                              },
                              icon: Icon(
                                Icons.arrow_forward_ios,
                                color: Colors.grey,
                                size: 12,
                              ),
                            )
                          ],
                        ),
                        1.gapV(Colors.grey[300]),
                        Row(
                          children: [
                            Text(
                              '用药天数',
                              style: leftTs,
                            ),
                            10.hGapDp,
                            Expanded(
                              child: StreamBuilder(
                                stream: bloc.useDayStream.stream,
                                builder:
                                    (context, AsyncSnapshot<int> snapshot) {
                                  return TextField(
                                    controller: useDayTC
                                      ..value.copyWith(
                                          text:
                                              snapshot?.data?.toString() ?? ''),
                                    keyboardType: TextInputType.number,
                                    textAlign: TextAlign.right,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        hintStyle: rightGreyTs,
                                        hintText: '请输入用药天数'),
                                    onChanged: (str) {
                                      bloc.setUseDay(str);
                                    },
                                  );
                                },
                              ),
                            ),
                            5.hGapDp,
                            Text(
                              '（天）',
                              style: rightTs,
                            ),
                          ],
                        ),
                        1.gapV(Colors.grey[300]),
                        Row(
                          children: [
                            Text(
                              '开药量',
                              style: leftTs,
                            ),
                            10.hGapDp,
                            Expanded(
                              child: StreamBuilder(
                                stream: bloc.medicineAmountStream.stream,
                                builder:
                                    (context, AsyncSnapshot<int> snapshot) {
                                  return TextField(
                                    controller: medicineNumTC
                                      ..value.copyWith(
                                          text:
                                              snapshot?.data?.toString() ?? ''),
                                    textAlign: TextAlign.right,
                                    keyboardType: TextInputType.number,
                                    decoration: InputDecoration(
                                        border: InputBorder.none,
                                        hintStyle: rightGreyTs,
                                        hintText: '请输入开药量'),
                                    onChanged: (str) {
                                      bloc.setMedicalNum(str);
                                    },
                                  );
                                },
                              ),
                            ),
                            5.hGapDp,
                            Text(
                              '（${item.productUnit}）',
                              style: rightTs,
                            ),
                          ],
                        ),
                        1.gapV(Colors.grey[300]),
                        10.vGapDp,
                        Text(
                          '备注',
                          style: leftTs.copyWith(fontSize: 16),
                        ),
                        10.vGapDp,
                        Container(
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                              color: Colors.grey[300],
                              borderRadius: BorderRadius.circular(10)),
                          child: StreamBuilder(
                            stream: bloc.remarkStream.stream,
                            builder: (context, AsyncSnapshot<String> snapshot) {
                              remarkTC ??= TextEditingController(
                                  text: snapshot?.data ?? item.memo);
                              return TextField(
                                controller: remarkTC
                                  ..value.copyWith(text: snapshot?.data ?? ''),
                                maxLines: 8,
                                maxLength: 200,
                                keyboardType: TextInputType.text,
                                textAlign: TextAlign.start,
                                style: rightTs,
                                decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintStyle: rightGreyTs,
                                    hintText: '如果有补充的内容，请在这里输入...'),
                                onChanged: (str) {
                                  bloc.setRemark(str);
                                },
                              );
                            },
                          ),
                        ),
                        50.vGapDp,
                        GestureDetector(
                          onTap: () {
                            bloc.doSave(context);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            height: 45,
                            margin: EdgeInsets.symmetric(horizontal: 30),
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: theme.themeColor.themeColor,
                                borderRadius: BorderRadius.circular(20)),
                            child: Text(
                              '保存',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        )
                      ],
                    );
            },
          ),
        ),
      ),
    );
  }

  @override
  EditMedicalBloc generateBloc() {
    return EditMedicalBloc();
  }
}
